<template>
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden"
        @onChange="contentChange"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
  </template>
  <script setup>
  import "@wangeditor/editor/dist/css/style.css"; // 引入 css
  import {
    defineProps,
    onBeforeUnmount,
    ref,
    shallowRef,
    onMounted,
    defineEmits,
    watch,
  } from "vue";
  import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
  import { getToken } from "@/utils/auth";
  // 内容 HTML
  const props = defineProps({
    mode: {
      type: String,
      default: "default",
    },
    modelValue: {
      type: String,
    },
  });
  const valueHtml = ref("");
  watch(() => props.modelValue,(v) => {
      if (v !== valueHtml.value) {
          valueHtml.value = v === undefined ? "" : v;
      }
    },
    { immediate: true }
  );
  const emit = defineEmits(["update:modelValue"]);
  const contentChange = (editor) => {
    emit("update:modelValue", editor.getHtml());
  }
  
  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef();
  // 模拟 ajax 异步获取内容
  onMounted(() => {
    // setTimeout(() => {
    //   valueHtml.value = "";
    // }, 1500);
  });
  const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload");
  const toolbarConfig = {};
  const editorConfig = {
    placeholder: "请输入内容...",
    MENU_CONF: {
      uploadImage: {
        server: uploadUrl.value,
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        fieldName: "file",
        customInsert(res, insertFn) {
          insertFn(import.meta.env.VITE_BASE_URL + res.fileName);
        },
      },
    },
  };
  
  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
  });
  
  const handleCreated = (editor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
  };
  </script> 